package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import top.littlejiang.onlinexam.common.base.Constant;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.PasswordUtils;
import top.littlejiang.onlinexam.entity.OlexamRole;
import top.littlejiang.onlinexam.entity.OlexamUser;
import top.littlejiang.onlinexam.entity.OlexamUserCourse;
import top.littlejiang.onlinexam.entity.OlexamUserRole;
import top.littlejiang.onlinexam.service.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author chen
 * @Description
 * @since 2021/3/7 13:21
 */
@Service
public class OlexamSysServiceImpl implements OlexamSysService {

    @Autowired
    OlexamUserService userService;
    @Autowired
    OlexamFileService fileService;
    @Autowired
    OlexamUserRoleService userRoleService;
    @Autowired
    OlexamRoleService roleService;
    @Autowired
    OlexamUserCourseService userCourseService;
    @Autowired
    OlexamCourseService courseService;

    /**
     * 管理员更新用户信息
     *
     * @param user
     * @param file
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateUser(OlexamUser user, MultipartFile file) {
        //保存文件
        if (!Objects.isNull(file)){
            String imgUrl = fileService.saveFile(file, Constant.PICTURE_URL);
            user.setUserPicture(imgUrl);
        }

        //修改角色
        if (user.getRoleId() != null){
            OlexamUserRole userRole = new OlexamUserRole();
            userRole.setFkUserId(user.getId());
            if (user.getRoleId() == 0){
                userRole.setFkRoleId(null);
            } else {
                userRole.setFkRoleId(user.getRoleId());
            }
            UpdateWrapper<OlexamUserRole> wrapper = new UpdateWrapper();
            wrapper.eq("fk_user_id", user.getId())
                    .set("fk_role_id", user.getRoleId())
                    .set("update_time", DateUtils.getTime());
            userRoleService.saveOrUpdate(userRole, wrapper);
        }

        //用户课程
        OlexamUser oldUser = userService.getBaseMapper().selectById(user.getId());
        if (!Objects.isNull(user.getFkClassId()) && user.getIsDel() == 0 && oldUser.getIsDel() == 1){
            List<Serializable> courseIds = courseService.getIdsByClass(user.getFkClassId(), null);
            List<OlexamUserCourse> userCourses = new ArrayList<>();
            courseIds.stream().forEach(item -> {
                OlexamUserCourse temp = new OlexamUserCourse();
                temp.setFkUserId(user.getId());
                temp.setFkCourseId((Integer)item);
                userCourses.add(temp);
            });
            userCourseService.saveBatch(userCourses, userCourses.size());
        }

        // 保存信息
        user.setUpdateTime(DateUtils.getTime());
        userService.updateById(user);
    }

    /**
     * 管理员更新角色相关信息
     *
     * @param role
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateOrInsertRole(OlexamRole role) {
        roleService.updateOrInsert(role);
    }

    /**
     * 新增一个用户
     *
     * @param user
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveOneUser(OlexamUser user) {
        if (StringUtils.isBlank(user.getUserSalty())){
            String userSalty = PasswordUtils.getRandomValue(PasswordUtils.DEFAULT_LENGTH);
            String userPwd = PasswordUtils.md5SaltyAndPwd(userSalty, user.getUserAccount().toString());
            user.setIsDel(0)
                    .setCreateTime(DateUtils.getTime())
                    .setUpdateTime(DateUtils.getTime())
                    .setUserPwd(userPwd)
                    .setUserSalty(userSalty);
        }
        userService.save(user);

        if (user.getFkClassId() > 0){
            List<Serializable> courseIds = courseService.getIdsByClass(user.getFkClassId(), null);
            if (!CollectionUtils.isEmpty(courseIds)){
                List<OlexamUserCourse> userCourses = new ArrayList<>();
                courseIds.stream().forEach(item -> {
                    OlexamUserCourse temp = new OlexamUserCourse();
                    temp.setFkCourseId((Integer)item);
                    temp.setFkUserId(user.getId());
                    userCourses.add(temp);
                });
                userCourseService.saveBatch(userCourses, userCourses.size());
            }
        }

        if (user.getRoleId() > 0){
            OlexamUserRole userRole = new OlexamUserRole();
            userRole.setFkRoleId(user.getRoleId());
            userRole.setFkUserId(user.getId());
            userRoleService.save(userRole);
        }
    }
}
